package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dto) {
        dishService.saveWithFlavor(dto);

        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R pageSelect(int page, int pageSize, String name) {
        //用MP提供的分页查询方法,方法内传入参数，
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //dish表没用菜品分类名称只有id，所以新建一个dto的查询，将基本的菜品信息复制到dto查询中
        Page<DishDto> dishDtoPage = new Page<>();
        //查询，新建查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //用工具类判断name是否为空
        queryWrapper.like(name != null, Dish::getName, name);
        //排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //调用service开始查询
        dishService.page(dishPage);

        //用工具类将两个分页查询互相拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //records指的是菜品信息及图片等数据，因为dish不含分类名称，数据需要处理
        List<Dish> records = dishPage.getRecords();
        //利用stream流进行查询
        List<DishDto> dtolist = records.stream().map((item) -> {
            //本次业务的目的就是将属性设置到Dto上,新建一个新的dto属性，赋值
            DishDto dishDto = new DishDto();
            //由于是新的对象，将item里面的值设置到dto里面
            BeanUtils.copyProperties(item, dishDto);
            //得到分类ID
            Long categoryId = item.getCategoryId();
            //利用Category的方法，得到分类对象，在通过对象获取分类名称
            Category category = categoryService.getById(categoryId);
            //得到分类name，为了安全，进行非空判断
            if (category != null) {
                String name1 = category.getName();
                //将分类名称设置到dto属性中
                dishDto.setCategoryName(name1);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dtolist);
        //返回dto分页查询
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R update(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("菜品信息修改成功");
    }

    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
       /* 请求url地址：/dish    ?ids=1504708761831292929,1504653856504483842

        请求方式：DELETE

        请求参数：?ids=1504708761831292929,1504653856504483842

        响应结果【格式统一】：R 对象*/
        dishService.removeByIds(ids);

        return R.success("删除成功");

    }

    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids) {
        // update dish set status = ? where id in (1,2,3)
        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus, status);// set status = ?
        qw.in(Dish::getId, ids);//  where id in (1,2,3)
        dishService.update(qw);

        // update dish set status = ? where id = ?
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("修改成功");
    }
    @GetMapping("/list")
    /* 在当前的需求中，我们只需要根据页面传递的菜品分类的ID(categoryId)来查询菜品列表即可，我们可以直接定义一个DishController的方法，
    声明一个Long类型的categoryId，这样做是没问题的。但是考虑到该方法的拓展性，我们在这里定义方法时，通过Dish这个实体来接收参数。*/
    public R<List<DishDto>> addSetmeal(DishDto dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }
}
